/*
 * @Description: 留言板路由
 * @Author: zheng yiliang
 * @Date: 2021-05-29 12:19:56
 * @LastEditTime: 2021-05-29 21:27:33
 * @LastEditors: zheng yiliang
 */

var express = require('express');
var router = express.Router();
const mongoose = require('../core/mongodb');

const { SuccessModel, ErrorModel } = require('../util')
const { Message } = require('../model')
const { PUBLIC_ERROR_MSG } = require('../core/constant');
const loginCheck = require('../middleware/loginCheck');
router.get('/allMsg', loginCheck, (req, res) => {
  const { pagenum, pagesize, is_handle } = req.query
  console.log(is_handle)
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 5
  let skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize;
  let condition = {}
  if (is_handle) {
    condition = { $or: [{ is_handle: is_handle * 1 }, { 'reply.is_handle': is_handle * 1 }] }
  }
  Message.countDocuments(condition, (err, count) => {
    if (err) {
      console.log('Error:' + err);
    } else {
      console.log(count)
      console.log(condition)
      Message.aggregate([
        {
          $lookup: {
            from: "webusers",
            localField: "user_id",
            foreignField: "user_id",
            as: "user"
          }
        },
        {
          $sort: { create_time: -1 }
        },
        {
          $skip: skip
        },
        {
          $limit: pageSize
        },
        {
          $match: condition
        }
      ], function (err, docs) {
        if (err) return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
        // if (is_handle * 1 === 1) {
        //   if (item.is_handle === 1 && item.reply.filter(ele => ele.is_handle === 2).length === 0) {
        //     return {
        //       name: item.user[0].name,
        //       id: item.user_id,
        //       headImg: item.user[0].avatar,
        //       comment: item.comment,
        //       time: item.create_time,
        //       like: item.likes,
        //       inputShow: false,
        //       _id: item._id,
        //       type: item.user[0].type,
        //       is_handle: item.is_handle,
        //       reply: item.reply ? item.reply.map(ele => {
        //         return {
        //           ...ele,
        //           inputShow: false
        //         }
        //       }) : []
        //     }
        //   }
        // }
        const messages = docs.map(item => {
          let reply = []
          if (is_handle * 1 === 1 && item.reply) {
            reply = item.reply.filter(ele => ele.is_handle === 1)
          } else if (is_handle * 1 === 2 && item.reply) {
            reply = item.reply.filter(ele => ele.is_handle === 2)
          } else {
            reply = item.reply
          }
          return {
            name: item.user[0].name,
            id: item.user_id,
            headImg: item.user[0].avatar,
            comment: item.comment,
            time: item.create_time,
            like: item.likes,
            inputShow: false,
            _id: item._id,
            type: item.user[0].type,
            is_handle: item.is_handle,
            reply: reply.map(ele => {
              return {
                ...ele,
                inputShow: false
              }
            })
          }
        })
        return res.json(new SuccessModel({ messages, count }, '留言板列表获取成功'))
      })
    }
  })

})

router.post('/replyMessage', loginCheck, (req, res) => {
  const item = {
    from: req.body.from,
    fromId: req.cookies.openid,
    fromAvatar: req.body.fromAvatar,
    fromType: 0,
    to: req.body.to,
    toId: req.body.toId,
    toType: 1,
    toAvatar: req.body.toAvatar,
    comment: req.body.comment,
    is_handle: 1
  }
  console.log(req.body)
  Message.findByIdAndUpdate(req.body._id, {
    $addToSet: {
      reply: item
    }
  }).then(data => {
    console.log(data)
    return res.json(new SuccessModel(data, '回复评论成功'))
  }).catch(err => {
    return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
  })
})

router.delete('/delReplyMessage', loginCheck, (req, res) => {
  const { replyId } = req.body
  console.log(req.body)
  Message.findByIdAndUpdate(req.body._id, {
    $pull: {
      reply: { _id: replyId }
    }
  }).then(data => {
    return res.json(new SuccessModel(data, '删除此留言成功'))
  }).catch(err => {
    console.log(err)
    return res.json(new ErrorModel(PUBLIC_ERROR_MSG))
  })
})

router.delete('/delMessage', loginCheck, (req, res) => {
  const { id } = req.body;
  Message.findByIdAndDelete(id).then(result => {
    return res.json(new SuccessModel('删除成功'))
  }).catch(err => {
    return res.json(new ErrorModel('删除失败'))
  });
})

router.put('/read', loginCheck, (req, res) => {
  Message.findByIdAndUpdate(req.body._id, {
    is_handle: 1
  }
  ).then(data => {
    return res.json(new SuccessModel('成功标记为已读'))
  }).catch(err => {
    return res.json(new ErrorModel('标记为已读失败'))

  })
})

router.put('/replyRead', loginCheck, (req, res) => {
  console.log(req.body)
  Message.updateOne({ _id: req.body._id, 'reply._id': req.body.replyId }, {
    $set: { "reply.$.is_handle": 1 }
  }).then(data => {
    if (data.nModified) {
      return res.json(new SuccessModel('成功标记为已读'))
    }
    return res.json(new ErrorModel('标记为已读失败'))
  }).catch(err => {

  })
})

router.put('/allRead', loginCheck, (req, res) => {
  console.log(req.body)
  Message.updateMany({ _id: req.body._id, 'reply.is_handle': 2 }, {
    $set: { "reply.$[].is_handle": 1 }
  }).then(data => {
    if (data.nModified) {
      return res.json(new SuccessModel('成功一键标记为已读'))
    }
    return res.json(new ErrorModel('一键标记为已读失败'))
  }).catch(err => {

  })
})

module.exports = router;
